import { PlusOutlined, TagsOutlined, DeleteOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Select, Modal, Tag, Spin, Badge } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import debounce from 'lodash.debounce';
import { PageContainer } from '@ant-design/pro-layout';
import { history } from 'umi';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { TableListItem, PlanItemParam } from './data.d';
import { planList, setTag, planRemove, batchDelete, planCopy, downloadZip } from './service';
import TagCommonComponent from '../System/components/TagCommonComponent';
import AssignTagsModel from '../System/components/AssignTagsModel';
import PlanReviewModel from './components/PlanReviewModel';

const { Search } = Input;
const { Option } = Select;

const PlanList: React.FC<{}> = () => {
  const [spinning, setSpinning] = useState<boolean>(false);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [copyModalVisible, handleCopyModalVisible] = useState<boolean>(false);
  const [assignTagModalVisible, handleAssignTagModalVisible] = useState<boolean>(false);
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [values, setValues] = useState<TableListItem>();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState<TableListItem[]>([]);
  const [tagEnabled, handleTagEnabled] = useState<boolean>(true);
  const [topOrgId, setTopOrgId] = useState<number>(0);

  const tagControl = () => {
    if (selectedRowKeys.length > 0) {
      for (let i in selectedRows) {
        if (parseInt(i) > 0) {
          const row1 = selectedRows[parseInt(i) - 1];
          const row = selectedRows[i];
          if (row1.topOrgId != row.topOrgId) {
            handleTagEnabled(true);
            return;
          }
        }
      }
      setTopOrgId(selectedRows[0].topOrgId);
      handleTagEnabled(false);
    } else {
      handleTagEnabled(true);
    }
  }

  useEffect(() => {
    tagControl();
  }, [selectedRowKeys, selectedRows]);

  //分配标签
  const assignTagCommand = (values: any) => {
    const tagsParam = new Object;
    tagsParam["planIds"] = selectedRowKeys.toString();
    tagsParam["tagIds"] = values.toString();
    new Promise((resolve, reject) => {
      setTag(tagsParam)
        .then((res) => {
          if (res.code === 200) {
            const hide = message.success('分配成功');
            handleAssignTagModalVisible(false);
            setSelectedRowKeys([]);
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
            hide();
            resolve(true);
          } else {
            message.error('分配失败，' + res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('删除失败');
          reject(error);
        });
    });
  }

  //标签选中监听
  const selectChange = (values: any, form: any) => {
    form.setFieldsValue({ "tagIds": values.toString() });
    form.submit();
  }

  //删除计划--删除弹出框
  const delConfirm = (id: number) => {
    const param = new Object();
    param["id"] = id;
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此计划将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          planRemove(param)
            .then((res) => {
              if (res) {
                if (res.code === 200) {
                  const hide = message.success('删除成功');
                  handleDeleteModalVisible(false);
                  if (selectedRowKeys.length > 0) {
                    for (var i in selectedRowKeys) {
                      if (selectedRowKeys[i] == id) {
                        selectedRowKeys.splice(parseInt(i), 1);
                      }
                    }
                  }
                  hide();
                  if (selectedRowKeys.length == 0) {
                    setSelectedRowKeys([]);
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  } else {
                    const newRows = selectedRows.concat();
                    for (let i = 0; i < selectedRows.length; i++) {
                      if (selectedRows[i].id == id) {
                        newRows.splice(i, 1);
                      }
                    }
                    setSelectedRows(newRows);
                    actionRef.current?.reload?.();
                  }
                  resolve(true);
                } else {
                  message.error('删除失败，' + res.message);
                  resolve(false);
                }
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };

  //批量删除计划--删除弹出框
  const delConfirmBatch = (ids: string) => {
    const param = new Object();
    param["ids"] = ids;
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此计划将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          batchDelete(param)
            .then((res) => {
              if (res) {
                if (res.code === 200) {
                  const errList = res.data;
                  if (errList.length == 0) {
                    message.success("删除成功", 1);
                  } else {
                    let mes = "";
                    for (let i in errList) {
                      for (let j in selectedRows) {
                        if (parseInt(selectedRows[j].id) == errList[i]) {
                          mes += selectedRows[j].name + '，';
                        }
                      }
                    }
                    mes = mes + "删除失败";
                    message.error(mes, 2);
                  }
                  handleDeleteModalVisible(false);
                  setSelectedRowKeys([]);
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                  resolve(true);
                } else {
                  message.error('删除失败，' + res.message);
                  resolve(false);
                }
              } else {
                message.error('删除失败');
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('请求失败');
              reject(error);
            });
        });
      },
    });
  };

  const copy = (id: number) => {
    setSpinning(true);
    new Promise((resolve, reject) => {
      planCopy(id)
        .then((res) => {
          setSpinning(false);
          if (res.code === 200) {
            const hide = message.success('复制成功');
            if (actionRef.current) {
              hide();
              actionRef.current.reload();
            }
            resolve(true);
          } else {
            message.error('复制失败');
            resolve(false);
          }
        })
        .catch((error) => {
          hide();
          message.error('复制失败');
          setSpinning(false);
          reject(error);
        });
    });
  }

  //计划复制
  const copyCommand = (record: TableListItem) => {
    const endDatetime = record.endDatetime;
    if (endDatetime) {
      const end = endDatetime.split(" ")[0].replace(/-/g, "");
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      let currentDate = year.toString() + (month >= 10 ? month.toString() : "0" + month) + (day >= 10 ? day.toString() : "0" + day);
      if (parseInt(end) >= parseInt(currentDate)) {
        copy(record.id);
      } else {
        Modal.confirm({
          visible: copyModalVisible,
          title: '确定复制',
          icon: <QuestionCircleOutlined />,
          content: '此计划结束时间已过期，在编辑计划中更改。',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            copy(record.id);
          },
        });
      }
    } else {
      copy(record.id);
    }
  };

  const requestDownloadUrl = (id: number,target:any) => {
    document.getElementById(id+"spin").style.display = "inline-block";
    target.style.display = "none";
    new Promise((resolve, reject) => {
      downloadZip(id)
        .then((res) => {
          setSpinning(false);
          if (res && res.code === 200) {
            const url = res.data;
            let link = document.createElement('a');
            link.innerHTML = "下载";
            link.setAttribute("target", "_blank");
            link.href = url;
            target.before(link);
            link.click();
            target.remove();
            document.getElementById(id+"spin")?.remove();
            resolve(true);
          } else {
            message.error('请求失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('复制失败');
          setSpinning(false);
          reject(error);
        });
    });
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '计划名称',
      dataIndex: 'name',
      // ellipsis: true,
      width: 150,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入计划名称"
              onSearch={debounce(value => { form.submit() }, 500)}
              onChange={debounce(value => { form.submit() }, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      render:  (_, record) => (
        record.defaultPlan == 0? record.name: (
          <Badge count="默认计划" style={{background:'#1890ff', color:'#fff',zIndex:9}} offset={[0, -10]}><label>{record.name}</label></Badge>)
      ),
      valueType: 'text',
    },
    {
      title: '发布状态',
      hideInTable: true,
      dataIndex: 'publishStatus',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              style={{ width: 200 }}
              placeholder="请选择"
              optionFilterProp="children"
              onChange={(value) => form.submit()}
            >
              <Option value="">所有状态</Option>
              <Option value="0">待发布</Option>
              <Option value="1">发布中</Option>
              <Option value="2">已完成</Option>
              <Option value="4">发布失败</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      // valueEnum: {
      // 0: { text: '待发布', status: 'Default' },
      // 1: { text: '发布中', status: 'Processing' },
      // 2: { text: '已完成', status: 'Success' },
      // 3: { text: '部分成功', status: 'Warning' },
      // 4: { text: '失败', status: 'Error' },
      // 5: { text: '已结束', status: 'Default' },
      // },
    },
    {
      title: '发布状态',
      dataIndex: 'publishStatusText',
      hideInSearch: true,
      valueEnum: {
        0: { text: '待发布', status: 'Default' },
        // 1: { text: '发布中', status: 'Processing' },
        2: { text: '已完成', status: 'Success' },
        // 3: { text: '部分成功', status: 'Warning' },
        4: { text: '发布失败', status: 'Error' },
        // 5: { text: '已结束', status: 'Default' },
      },
    },
    {
      title: '审核状态',
      dataIndex: 'auditStatus',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              style={{ width: 200 }}
              placeholder="请选择"
              optionFilterProp="children"
              onChange={(value) => form.submit()}
            >
              <Option value="">所有状态</Option>
              <Option value="0">待审核</Option>
              <Option value="1">已通过</Option>
              <Option value="2">已拒绝</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueEnum: {
        0: { text: '待审核', status: 'Processing' },
        1: { text: '已通过', status: 'Success' },
        2: { text: '已拒绝', status: 'Error' },
      },
    },
    {
      title: '发布方式',
      dataIndex: 'publishWay',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              optionFilterProp="children"
              style={{ width: 200 }}
              placeholder="请选择"
              onChange={(value) => form.submit()}
            >
              <Option value="">所有状态</Option>
              <Option value="0">实时发布</Option>
              <Option value="1">定时发布</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueEnum: {
        0: { text: '实时发布' },
        1: { text: '定时发布' },
      },
    },
    {
      title: '标签',
      dataIndex: 'tagIds',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <TagCommonComponent
              topOrgId={JSON.parse(localStorage.getItem("user")).topOrgId}
              selectChange={(values) => selectChange(values, form)}>
            </TagCommonComponent>
          );
        }
        return defaultRender(_);
      },
      hideInTable: true,
      valueType: 'text',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      width: 150,
      hideInSearch: true,
      render: tags => (
        <>
          {tags?.map((tag, index) => {
            return (
              <Tag color="blue" key={index} title={tag.name} style={{ marginBottom: 5, display: 'inline-block', overflow: 'hidden', whiteSpace: 'pre', textOverflow: 'ellipsis', maxWidth: 130 }}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '发布类型',
      dataIndex: 'publishType',
      hideInSearch: true,
      valueEnum: {
        0: { text: '独立发布' },
        1: { text: '同步发布' },
      },
    },
    {
      title: '播放模式',
      dataIndex: 'playMode',
      hideInSearch: true,
      valueEnum: {
        0: { text: '持续播放' },
        1: { text: '按时段播放' },
      },
    },
    {
      title: '播放日期',
      dataIndex: 'playDatetime',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '作者',
      dataIndex: 'userNickname',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '审核人',
      dataIndex: 'auditorNickname',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateDatetime',
      valueType: 'dateTime',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              record['type'] = 'plan';
              setValues(record)
            }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <a
            // disabled={record.auditStatus == 1?true:false}
            onClick={() => {
              history.push({ pathname: '/plan/list/new/', state: record });
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              copyCommand(record);
            }}
          >
            复制
          </a>
          <Divider type="vertical" />
          {record.zipFile ? (
            <a
              disabled={record.auditStatus == 0 ? true : false}
              href={record.zip}
              target="_blank"
            >
              下载
            </a>

          ) : (
            <>
            <Spin id={record.id+"spin"} size="small" style={{display:'none'}}></Spin>
            <a
              disabled={record.auditStatus == 0 ? true : false}
              onClick={(e) => {
                requestDownloadUrl(record.id,e.target);
              }}
              target="_blank"
            >
              下载
            </a>
            </>
          )}

          <Divider type="vertical" />
          <a
            onClick={() => {
              delConfirm(record.id);
            }}>删除</a>
        </>
      ),
    },
  ];

  return (
    <Spin spinning={spinning} tip="如果该计划引用的节目过大可能需要几分钟，复制中请耐心等待..." size="large" style={{ marginTop: '20vh', fontSize: 16 }}>
      <PageContainer>
        <ProTable<TableListItem>
          options={false}
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 120,
          }}
          pagination={{ showQuickJumper: true, defaultPageSize: 10 }}
          toolBarRender={() => [
            <Button type="primary" onClick={() => history.push('/plan/list/new')}>
              <PlusOutlined /> 新建计划
            </Button>,
            <Button type="primary"
              disabled={tagEnabled}
              onClick={() => handleAssignTagModalVisible(true)}
            >
              <TagsOutlined /> 分配标签
            </Button>,
            <Button type="primary"
              disabled={selectedRows.length > 0 ? false : true}
              onClick={() => delConfirmBatch(selectedRows.map((row) => row.id).toString())}
            >
              <DeleteOutlined /> 批量删除
            </Button>,
          ]}
          request={(params, sorter, filter) => planList(params, sorter, filter)}
          columns={columns}
          onLoad={() => {
            setSelectedRowKeys(selectedRowKeys);
            setSelectedRows(selectedRows);
          }}
          rowSelection={{
            selectedRowKeys: selectedRowKeys,
            onSelect: (record, selected) => {
              if (selected) {//选中
                setSelectedRowKeys([...selectedRowKeys, record.key]);
                setSelectedRows([...selectedRows, record]);
              } else {//取消选中
                const newKeys = selectedRowKeys.concat();
                const index = newKeys.indexOf(record.key);
                newKeys.splice(index, 1);
                setSelectedRowKeys(newKeys);

                const newRows = selectedRows.concat();
                for (let i = 0; i < selectedRows.length; i++) {
                  if (i == index) {
                    newRows.splice(index, 1);
                  }
                }
                setSelectedRows(newRows);
              }
            },
            onSelectAll: (selected, selectedRows1, changeRows) => {
              if (selected) {//全选
                const keys = [];
                for (let i = 0; i < changeRows.length; i++) {
                  const record = changeRows[i];
                  keys.push(record.key);
                }
                setSelectedRowKeys([...selectedRowKeys, ...keys]);
                setSelectedRows([...selectedRows, ...changeRows]);
              } else {//取消全选
                const newSelectedRowKeys = selectedRowKeys.concat();
                const newSelectedRows = selectedRows.concat();
                for (let i = 0; i < changeRows.length; i++) {
                  const record = changeRows[i];
                  for (let j = 0; j < newSelectedRowKeys.length; j++) {
                    if (record.key == newSelectedRowKeys[j]) {
                      newSelectedRowKeys.splice(j, 1);
                      newSelectedRows.splice(j, 1);
                    }
                  }
                }
                setSelectedRowKeys(newSelectedRowKeys);
                setSelectedRows(newSelectedRows);
              }
            }
          }}
          tableAlertOptionRender={() => {
            return (<a onClick={() => {
              setSelectedRowKeys([]);
              setSelectedRows([]);
              actionRef.current?.clearSelected?.();
            }}>清空</a>)
          }}
        />
        <AssignTagsModel
          modalVisible={assignTagModalVisible}
          topOrgId={topOrgId}
          onSubmit={assignTagCommand}
          onCancel={() => handleAssignTagModalVisible(false)}
        >
          <ProTable<TableListItem, TableListItem> />
        </AssignTagsModel>
        <PlanReviewModel
          values={values}
          onApproved={(e) => console.log(e)}
          onReject={(e) => console.log(e)}
          onCancel={() => handleModalVisible(false)}
          modalVisible={modalVisible}>
          <ProTable<PlanItemParam, PlanItemParam>
          />
        </PlanReviewModel>
      </PageContainer>
    </Spin>
  );
};

export default PlanList;
